"use client"

import { useEffect, useState } from "react"
import { useParams } from "next/navigation"
import { getRankingDetail } from "@/lib/api-client"
import { Skeleton } from "@/components/ui/skeleton"
import { Pagination } from "@/components/ui/pagination"
import type { Song } from "@/types"
import { PlayIcon } from "@/components/icons"
import { usePlayerContext } from "@/contexts/player-context"

export default function RankingDetailPage() {
  const params = useParams()
  const id = params.id as string
  const [songs, setSongs] = useState<Song[] | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState<string | null>(null)
  const [rankingInfo, setRankingInfo] = useState<{
    name: string
    description: string
    updateTime: string
    updateFrequency: string
    backgroundColor?: string
  } | null>(null)
  const [page, setPage] = useState(1)
  const [totalPages, setTotalPages] = useState(1)
  const pageSize = 20 // 每页显示20首歌曲
  const { playSong } = usePlayerContext()

  useEffect(() => {
    async function fetchRankingDetail() {
      try {
        setLoading(true)
        const response = await getRankingDetail(id)

        if (response.success) {
          // 设置排行榜信息
          if (response.rankingInfo) {
            setRankingInfo({
              name: response.rankingInfo.name,
              description: response.rankingInfo.description,
              updateTime: response.rankingInfo.updateTime,
              updateFrequency: response.rankingInfo.updateFrequency,
              backgroundColor: response.rankingInfo.backgroundColor,
            })
          }

          if (response.data) {
            // 计算总页数
            const total = response.data.length
            setTotalPages(Math.ceil(total / pageSize))

            // 获取当前页的歌曲
            const startIndex = (page - 1) * pageSize
            const endIndex = startIndex + pageSize
            setSongs(response.data.slice(startIndex, endIndex))
          }
        } else {
          setError("获取排行榜详情失败")
        }
      } catch (err) {
        setError("获取排行榜详情失败")
        console.error(err)
      } finally {
        setLoading(false)
      }
    }

    fetchRankingDetail()
  }, [id, page])

  const handlePageChange = (newPage: number) => {
    setPage(newPage)
  }

  // 使用排行榜返回的背景颜色，如果有的话
  const headerStyle = rankingInfo?.backgroundColor
      ? { backgroundColor: rankingInfo.backgroundColor }
      : { backgroundColor: "#e13e74" }

  if (loading) {
    return (
        <div className="container py-6">
          <Skeleton className="h-40 w-full mb-6 rounded-lg" />
          <Skeleton className="h-8 w-48 mb-4" />
          {Array.from({ length: 10 }).map((_, i) => (
              <Skeleton key={i} className="h-16 w-full mb-2" />
          ))}
        </div>
    )
  }

  if (error) {
    return (
        <div className="container py-6">
          <div className="text-red-500 p-4">{error}</div>
        </div>
    )
  }

  return (
      <div className="container py-6">
        <div className="rounded-lg p-6 text-white mb-6" style={headerStyle}>
          <h1 className="text-3xl font-bold mb-2">{rankingInfo?.name}</h1>
          <p className="mb-4">{rankingInfo?.description}</p>
          <div className="text-sm opacity-80">
            {rankingInfo?.updateFrequency} · {rankingInfo?.updateTime}
          </div>
        </div>

        <div className="bg-background rounded-lg p-6">
          <h2 className="text-xl font-bold mb-4">歌曲列表</h2>

          <div className="space-y-2">
            {songs?.map((song, index) => (
                <div key={song.id} className="flex items-center p-2 hover:bg-muted rounded-md group">
                  <div className="w-8 text-center text-muted-foreground">{(page - 1) * pageSize + index + 1}</div>
                  <div className="flex-1 min-w-0 ml-4">
                    <div className="font-medium truncate">{song.title}</div>
                    <div className="text-sm text-muted-foreground truncate">{song.artists}</div>
                  </div>
                  <button
                      className="p-2 opacity-0 group-hover:opacity-100 transition-opacity"
                      onClick={() => playSong(song)}
                  >
                    <PlayIcon className="h-5 w-5" />
                  </button>
                </div>
            ))}
          </div>

          {totalPages > 1 && (
              <div className="mt-6 flex justify-center">
                <Pagination currentPage={page} totalPages={totalPages} onPageChange={handlePageChange} />
              </div>
          )}
        </div>
      </div>
  )
}

